<template>
  <div class="addMerchantBox" v-loading="loading">
    <el-button
      class="el-icon-arrow-left"
      size="mini"
      type="primary"
      style="margin-bottom:10px;"
      @click="handBackList"
    >返回</el-button>
    <el-form ref="form" :model="initial_data" :rules="rules">
      <el-form-item label="权限名字" prop="name">
        <el-input v-model="initial_data.name" style="width:300px" placeholder="请输入角色名字"></el-input>
      </el-form-item>

      <el-form-item label="上级权限" prop="pid">
        <SelectTree 
          :props="props"
          :options="permissionList"
          :value="valueId"
          :clearable="isClearable"
          :accordion="isAccordion"
          @getValue="getValue($event)"/>
      </el-form-item>

      <el-form-item label="节点" prop="rule" style="width:100%;">
          <el-select multiple="multiple" style="width:300px" v-model="initial_data.rule" placeholder="请选择节点（可多选）">
          <el-option
            v-for="(item) in ruleList"
            :key="item.id"
            :label="item.url"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
    </el-form>

    <div class="submitBtnBox">
      <el-button class="submitBtn" @click="submitFn" type="primary">确认添加</el-button>
    </div>
  </div>
</template>

<script>
import SelectTree from "../../components/SelectTree/index.vue";
export default {
  name: "permission-permission-update",
  components: {
    SelectTree
  },
  data() {
    return {
      isClearable:true,     // 可清空（可选）
      isAccordion:true,     // 可收起（可选）
      valueId:0,            // 初始ID（可选）
      props:{               // 配置项（必选）
        value: 'id',
        label: 'label',
        children: 'children',
        // disabled:true
      },
      initial_data: {
        //获取初始数据
        name: "",
        rule: [],
        pid: ''
      },
      ruleList: [],
      permissionList: [],
      loading: false,
      rules: {
        name: [{ required: true, message: "请输入角色名称", trigger: "blur" }],
        pid: [{ required: true, message: "请选择上级", trigger: "blur" }],
        rule: [{ required: true, message: "请选择权限", trigger: "blur" }]
      },
    };
  },
  computed:{
    optionData(){
      let cloneData = JSON.parse(JSON.stringify(this.list))      // 对源数据深度克隆
      return  cloneData.filter(father=>{                      // 循环所有项，并添加children属性
          let branchArr = cloneData.filter(child=>father.id == child.parentId);       // 返回每一项的子级数组
          branchArr.length>0 ? father.children=branchArr : ''   //给父级添加一个children属性，并赋值
          return father.parentId==0;      //返回第一层
      });
    }
  },
  methods: {
    getValue(value){
      this.valueId = value
      console.log(this.valueId);
    },
    getPermissionInfo(){
        this.$http.get("/web/user/permissions/url", {
          params: {
            token: localStorage.getItem("user_token"),
            id: this.$route.query.id
          }
        })
        .then(response => {
            if (response.data.status == "success") {
                this.initial_data = response.data.data;
                this.valueId = parseInt(response.data.data.pid.join(','));
                this.initial_data.token = localStorage.getItem("user_token");
            }
        })
        .catch(error => {
          console.log("error:", error);
        });
    },
    getPermission(){
        this.$http.get("/web/user/permissions/list/tree", {
          params: {
            token: localStorage.getItem("user_token")
          }
        })
        .then(response => {
          
            if (response.data.status == "success") {
                this.permissionList = response.data.data;
                this.permissionList.push({ id: 0, label: '没有上级' })
            }
        })
        .catch(error => {
          console.log("error:", error);
        });
    },
    //获取下拉Url节点
    getUrl() {
        
      this.$http
        .get("/web/user/url/list", {
          params: {
            token: localStorage.getItem("user_token")
          }
        })
        .then(response => {
          if (response.data.status == "success") {
            this.ruleList = response.data.data;
          }
        })
        .catch(error => {
          console.log("error:", error);
        });
    },

    handBackList() {
      this.$router.push({ name: "permission" });
    },

    submitFn() {
        console.log(this.initial_data);return;
      this.$refs.form.validate(valid => {
        if (!valid) {
          return false;
        } else {
          this.loading = true;
          this.$nextTick(() => {
            this.$http
              .post("/web/user/permissions/add", this.initial_data)
              .then(response => {
                if (response.data.status == "success") {
                  this.$message({
                    message: "修改成功",
                    duration: 6000
                  });

                  this.$router.push({
                    name: "permission"
                  });
                } else {
                  this.$message({
                    message: "修改失败，原因：" + response.data.failedMsg,
                    duration: 6000
                  });
                }
                this.loading = false;
              })
              .catch(error => {
                this.$message({
                  message: "添加失败，原因：" + error,
                  duration: 6000
                });
                this.loading = false;
              });
          });
        }
      });
    }
  },
  mounted() {
    this.getPermissionInfo();
    this.getUrl();
    this.getPermission();
  }
};
</script>

<style scoped lang="scss">

@import "./permission.scss";
  .el-scrollbar .el-scrollbar__view .el-select-dropdown__item{
    height: auto;
    max-height: 274px;
    padding: 0;
    overflow: hidden;
    overflow-y: auto;
  }
  .el-select-dropdown__item.selected{
    font-weight: normal;
  }
  ul li >>>.el-tree .el-tree-node__content{
    height:auto;
    padding: 0 20px;
  }
  .el-tree-node__label{
    font-weight: normal;
  }
  .el-tree >>>.is-current .el-tree-node__label{
    color: #409EFF;
    font-weight: 700;
  }
  .el-tree >>>.is-current .el-tree-node__children .el-tree-node__label{
    color:#606266;
    font-weight: normal;
  }
</style>
